import axios from "axios";
import { ElLoading } from 'element-plus'
import store from "@/store";
import Message from "@/utils/Message"
import router from "@/router/index.js"
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'


const service = axios.create({
    baseURL: "/api",
    timeout: 30 * 1000,
})

// //请求前过滤器

// let loading=null;
service.interceptors.request.use(
    (config) => {
        
        let token = localStorage.getItem("token")
        if (token) {
            config.headers['Authorization'] ="Bearer " + token // 让每个请求携带自定义token 请根据实际情况自行修改
        }
        if (config.showLoading) {
            loading = ElLoading.service({
                lock: true,
                text: "加载中......",
                background: 'rgba(0,0,0,0.7)'
            })
        }
        return config;
    }, (error) => {
        if (error.config.showLoading && loading) {
            loading.close();
        }
        Message.error("请求发送失败");
        return Promise.reject("请求发送失败");
    }



);

// //请求后过滤器
service.interceptors.response.use(
    (response) => {
        console.log(response,"llll")
        if (response.data.code != "1") {
          
            Message.error(response.data.msg)
            if (response.data.code == "614") {
                // Message.error(response.data.msg)
                localStorage.removeItem("userInfo")
                localStorage.removeItem("token")   
               
                setTimeout(() => {
                    router.push("/") 
                    router.go(0)
                }, 500);
            }
            if(response.data.code == "613" && !response.config.url.includes("/articles/support") && !response.config.url.includes("/comments")){
                setTimeout(() => {
                router.push("/") 
            }, 500);
            }
        }
        // if (response.data.code != "613") {
        //    router.push("/")
        // }
        if (response.data.code == "1") {
            return response.data
        }

       
       


    }, (error) => {
        
        return Promise.reject({ showError: true, msg: "网络异常" });
    }

);


export default service;